package club.lemos.sso.web.rest;

import club.lemos.sso.config.security.common.LopUserDetails;
import club.lemos.sso.config.security.jwt.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 根据 token, 获取本地用户详细信息(UserDetails)
 *
 */
@RestController
public class LopUserDetailsRestController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource(name = "lopUserDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    /**
     * 注意不能通过 url访问,需要使用 ajax设置请求头
     *
     * hasRole前面方法原理:
     * Collection<? extends GrantedAuthority> userAuthorities = this.authentication.getAuthorities();
     * Principle 对象中存储着角色的信息,跟 UserDetails相关
     *
     * 批量的权限管理,参考 spel表达式
     *
     * @param request 请求
     * @return 授访问用户信息 UserDetails
     */
    @PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public LopUserDetails getAuthenticatedUser(HttpServletRequest request) {

        String token = request.getHeader(tokenHeader);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        LopUserDetails user = (LopUserDetails) userDetailsService.loadUserByUsername(username);
        return user;
    }

}
